<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Ajax总结篇 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,Ajax,">
  

  <meta name="description" content="原文出处 http://blog.poetries.top/2016/11/26/Ajax-summary  本文主要总结整理Ajax的一些常用的基础知识，适合初学者。 一、Ajax简介、优劣势、应用场景以及技术 Ajax简介 :  Asynchronous Javascript And XML （异步的JavaScript和XML） 它并不是一种单一的技术，而是有机利用一系列交互式网页应用相关">
<meta name="keywords" content="JavaScript,Ajax">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax总结篇">
<meta property="og:url" content="http://blog.poetries.top/2016/11/26/Ajax-summary/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="原文出处 http://blog.poetries.top/2016/11/26/Ajax-summary  本文主要总结整理Ajax的一些常用的基础知识，适合初学者。 一、Ajax简介、优劣势、应用场景以及技术 Ajax简介 :  Asynchronous Javascript And XML （异步的JavaScript和XML） 它并不是一种单一的技术，而是有机利用一系列交互式网页应用相关">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/11.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/12.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/13.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/14.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/15.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20191001/16.png">
<meta property="og:updated_time" content="2020-08-15T04:25:31.898Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Ajax总结篇">
<meta name="twitter:description" content="原文出处 http://blog.poetries.top/2016/11/26/Ajax-summary  本文主要总结整理Ajax的一些常用的基础知识，适合初学者。 一、Ajax简介、优劣势、应用场景以及技术 Ajax简介 :  Asynchronous Javascript And XML （异步的JavaScript和XML） 它并不是一种单一的技术，而是有机利用一系列交互式网页应用相关">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/20191001/11.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#一、Ajax简介、优劣势、应用场景以及技术"><span class="toc-text">一、Ajax简介、优劣势、应用场景以及技术</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#二、创建ajax的步骤"><span class="toc-text">二、创建ajax的步骤</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1、创建XMLHttpRequest对象"><span class="toc-text">1、创建XMLHttpRequest对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2、准备请求"><span class="toc-text">2、准备请求</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3、发送请求"><span class="toc-text">3、发送请求</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4、处理响应"><span class="toc-text">4、处理响应</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5、封装例子"><span class="toc-text">5、封装例子</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#谈谈JSONP"><span class="toc-text">谈谈JSONP</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#三、-jQuery中的Ajax"><span class="toc-text">三、 jQuery中的Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#jQuery中的Ajax的一些方法"><span class="toc-text">jQuery中的Ajax的一些方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#load-方法"><span class="toc-text">load()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#get-和-post-方法"><span class="toc-text">$.get()和$.post()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ajax-方法"><span class="toc-text">$.ajax()方法</span></a></li></ol></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-Ajax-summary" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Ajax总结篇</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2016.11.26</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 4.8k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 20分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <blockquote>
<p>原文出处 <a href="http://blog.poetries.top/2016/11/26/Ajax-summary">http://blog.poetries.top/2016/11/26/Ajax-summary</a></p>
</blockquote>
<p>本文主要总结整理<code>Ajax</code>的一些常用的基础知识，适合初学者。</p>
<h3 id="一、Ajax简介、优劣势、应用场景以及技术"><a href="#一、Ajax简介、优劣势、应用场景以及技术" class="headerlink" title="一、Ajax简介、优劣势、应用场景以及技术"></a>一、Ajax简介、优劣势、应用场景以及技术</h3><ul>
<li><p>Ajax简介 :</p>
<ul>
<li><code>Asynchronous Javascript And XML</code> （异步的<br><code>JavaScript</code>和<code>XML</code>）</li>
<li>它并不是一种单一的技术，而是有机利用一系列交互式网页应用相关的技术所形成的结合体</li>
<li><code>AJAX</code> 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换，<code>AJAX</code> 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。</li>
</ul>
</li>
<li><p>优点：</p>
<ul>
<li>页面无刷新，用户体验好。</li>
<li>异步通信，更加快的响应能力。</li>
<li>减少冗余请求，减轻了服务器负担</li>
<li>基于标准化的并被广泛支持的技术，不需要下载插件或者小程序</li>
</ul>
</li>
<li><p>缺点：</p>
<ul>
<li><code>ajax</code>干掉了<code>back</code>按钮，即对浏览器后退机制的破坏。</li>
<li>存在一定的安全问题。</li>
<li>对搜索引擎的支持比较弱。</li>
<li>破坏了程序的异常机制。</li>
<li>无法用<code>URL</code>直接访问</li>
</ul>
</li>
<li><p><code>ajax</code>应用场景</p>
<ul>
<li>场景 1. 数据验证</li>
<li>场景 2. 按需取数据</li>
<li>场景 3. 自动更新页面</li>
</ul>
</li>
<li><p><code>AJAX</code> 包含以下五个部分：<br><code>ajax</code>并非一种新的技术，而是几种原有技术的结合体。它由下列技术组合而成。</p>
<ul>
<li>使用<code>CSS</code>和<code>XHTML</code>来表示。</li>
<li>使用<code>DOM</code>模型来交互和动态显示。</li>
<li>数据互换和操作技术，使用<code>XML</code>与<code>XSLT</code></li>
<li>使用<code>XMLHttpRequest</code>来和服务器进行异步通信。</li>
<li>使用<code>javascript</code>来绑定和调用。</li>
</ul>
</li>
</ul>
<p>在上面几中技术中，除了<code>XmlHttpRequest</code>对象以外，其它所有的技术都是基于<code>web</code>标准并且已经得到了广泛使用的，<code>XMLHttpRequest</code>虽然目前还没有被<code>W3C</code>所采纳，但是它已经是一个事实的标准，因为目前几乎所有的主流浏览器都支持它</p>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/11.png" alt></p>
<ul>
<li>第一张图尤其说明了传统<code>Web</code> 应用程序的结构与采用了 <code>AJAX</code> 技术的 <code>Web</code><br>应用程序的结构上的差别</li>
<li>主要的差别，其实不是 <code>JavaScript</code>，不是 <code>HTML/XHTML</code>和 <code>CSS</code>，而是采用<br>了 <code>XMLHttpRequest</code> 来向服务器异步的请求 <code>XML</code> 数据</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/12.png" alt></p>
<ul>
<li>再来看第二张图，传统的 <code>Web</code> 应用模式，用户的体验是割裂的，点击-&gt;等待-&gt;<br>看到新的页面-&gt;再点击-&gt;再等待。而采用了<code>AJAX</code>技术之后，大部分的计算工作，都是在用户不察觉的情况下，交由服务器去完成了</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/13.png" alt></p>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/14.png" alt></p>
<h3 id="二、创建ajax的步骤"><a href="#二、创建ajax的步骤" class="headerlink" title="二、创建ajax的步骤"></a>二、创建ajax的步骤</h3><blockquote>
<p><code>Ajax</code>的原理简单来说通过<code>XmlHttpRequest</code>对象来向服务器发异步请求，从服务器获得数据，然后用<code>javascript</code>来操作<code>DOM</code>而更新页面。这其中最关键的一步就是从服务器获得请求数据。原生创建<code>ajax</code>可分为以下四步</p>
</blockquote>
<h4 id="1、创建XMLHttpRequest对象"><a href="#1、创建XMLHttpRequest对象" class="headerlink" title="1、创建XMLHttpRequest对象"></a>1、创建<code>XMLHttpRequest</code>对象</h4><p><code>Ajax</code>的核心是<code>XMLHttpRequest</code>对象，它是<code>Ajax</code>实现的关键，发送异步请求、接受响应以及执行回调都是通过它来完成</p>
<p>所有现代浏览器（IE7+、Firefox、Chrome、Safari 以及 Opera）均内建 XMLHttpRequest 对象。</p>
<ul>
<li><p>创建 <code>XMLHttpRequest</code>对象的语法：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br></pre></td></tr></table></figure>
</li>
<li><p>老版本的 <code>Internet Explorer</code>（IE5 和 IE6）使用<code>ActiveX</code> 对象：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> ActiveXObject(<span class="string">"Microsoft.XMLHTTP"</span>);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>为了应对所有的现代浏览器，包括 <code>IE5</code> 和 <code>IE6</code>，请检查浏览器是否支持 <code>XMLHttpRequest</code>对象。如果支持，则创建<code>XMLHttpRequest</code>对象。如果不支持，则创建<code>ActiveXObject</code>：</p>
<ul>
<li>兼容各个浏览器的创建<code>Ajax</code>的工具函数</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createRequest</span> (<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">	&#125;<span class="keyword">catch</span> (tryMS)&#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			xhr = <span class="keyword">new</span> ActiveXObject(<span class="string">"Msxm12.XMLHTTP"</span>);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (otherMS) &#123;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				xhr = <span class="keyword">new</span> ActiveXObject(<span class="string">"Microsoft.XMLHTTP"</span>);</span><br><span class="line">			&#125;<span class="keyword">catch</span> (failed) &#123;</span><br><span class="line">				xhr = <span class="literal">null</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> xhr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2、准备请求"><a href="#2、准备请求" class="headerlink" title="2、准备请求"></a>2、准备请求</h4><ul>
<li><p>初始化该<code>XMLHttpRequest</code>对象，接受三个参数：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.open(method,url,<span class="keyword">async</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>第一个参数表示请求类型的字符串，其值可以是<code>GET</code>或者<code>POST</code>。</p>
</li>
<li><p><code>GET</code>请求：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.open(<span class="string">"GET"</span>,demo.php?name=tsrot&amp;age=<span class="number">24</span>,<span class="literal">true</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>POST</code>请求：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.open(<span class="string">"POST"</span>,demo.php,<span class="literal">true</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>第二个参数是要作为请求发送目标的URL。</p>
</li>
<li>第三个参数是<code>true</code>或<code>false</code>，表示请求是以异步还是同步的模式发出。（默认为<code>true</code>，一般不建议为<code>false</code>）<ul>
<li><code>false</code>：同步模式发出的请求会暂停所有javascript代码的执行，知道服务器获得响应为止，如果浏览器在连接网络时或者在下载文件时出了故障，页面就会一直挂起。 </li>
<li><code>true</code>：异步模式发出的请求，请求对象收发数据的同时，浏览器可以继续加载页面，执行其他javascript代码</li>
</ul>
</li>
</ul>
<h4 id="3、发送请求"><a href="#3、发送请求" class="headerlink" title="3、发送请求"></a>3、发送请求</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.send();</span><br></pre></td></tr></table></figure>
<p>一般情况下，使用<code>Ajax</code>提交的参数多是些简单的字符串，可以直接使用<code>GET</code>方法将要提交的参数写到<code>open</code>方法的<code>url</code>参数中，此时<code>send</code>方法的参数为<code>null</code>或为空。</p>
<ul>
<li><p><code>GET</code>请求：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.open(<span class="string">"GET"</span>,demo.php?name=tsrot&amp;age=<span class="number">24</span>,<span class="literal">true</span>);</span><br><span class="line">xhr.send(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>POST</code>请求：<br>如果需要像 <code>HTML</code> 表单那样 <code>POST</code> 数据，请使用 <code>setRequestHeader()</code>来添加 <code>HTTP</code> 头。然后在<code>send()</code>方法中规定您希望发送的数据：</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.open(<span class="string">"POST"</span>,demo.php,<span class="literal">true</span>);</span><br><span class="line">xhr.setRequestHeder(<span class="string">"Content-Type"</span>,<span class="string">"application/x-www-form-urlencoded;charset=UTF-8"</span>);</span><br><span class="line">xhr.sen</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4、处理响应"><a href="#4、处理响应" class="headerlink" title="4、处理响应"></a>4、处理响应</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(xhr.readyState == <span class="number">4</span> &amp;&amp; xhr.status == <span class="number">200</span>)&#123;</span><br><span class="line">		<span class="built_in">console</span>.log(xhr.responseText);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p><code>onreadystatechange</code> ：当处理过程发生变化的时候执行下面的函数</p>
</li>
<li><p><code>readyState</code> ：<code>ajax</code>处理过程</p>
<ul>
<li>0：请求未初始化（还没有调用 <code>open()</code>）。</li>
<li>1：请求已经建立，但是还没有发送（还没有调用 <code>send()</code>）。</li>
<li>2：请求已发送，正在处理中（通常现在可以从响应中获取内容头）。</li>
<li>3：请求在处理中；通常响应中已有部分数据可用了，但是服务器还没有完成响应的生成。</li>
<li>4：响应已完成；您可以获取并使用服务器的响应了。</li>
</ul>
</li>
<li><p><code>status</code>属性：</p>
<ul>
<li>200:”OK”</li>
<li>404: 未找到页面</li>
</ul>
</li>
<li><p><code>responseText</code>：获得字符串形式的响应数据</p>
</li>
<li><code>responseXML</code>：获得 <code>XML</code>形式的响应数据</li>
<li>对象转换为JSON格式使用<code>JSON.stringify</code></li>
<li><code>json</code>转换为对象格式用<code>JSON.parse()</code></li>
<li><p>返回值一般为<code>json</code>字符串，可以用<code>JSON.parse(xhr.responseText)</code>转化为<code>JSON</code>对象</p>
</li>
<li><p><strong>从服务器传回的数据是json格式，这里做一个例子说明，如何利用</strong></p>
<ul>
<li>1、首先需要从<code>XMLHttpRequest</code>对象取回数据这是一个<code>JSON</code>串，把它转换为真正的<code>JavaScript</code>对象。使用<code>JSON.parse(xhr.responseText)</code>转化为<code>JSON</code>对象</li>
<li>2、遍历得到的数组，向<code>DOM</code>中添加新元素</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">example</span>(<span class="params">responseText</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> saleDiv= <span class="built_in">document</span>.getElementById(<span class="string">"sales"</span>);</span><br><span class="line"><span class="keyword">var</span> sales = <span class="built_in">JSON</span>.parse(responseText);</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;sales.length;i++)&#123;</span><br><span class="line">        <span class="keyword">var</span> sale = sales[i];</span><br><span class="line">         <span class="keyword">var</span> div = <span class="built_in">document</span>.createElement(<span class="string">"div"</span>);</span><br><span class="line">         div.setAttribute(<span class="string">"class"</span>,<span class="string">"salseItem"</span>);</span><br><span class="line">        div.innerHTML = sale.name + sale.sales;</span><br><span class="line">        salseDiv.appendChild(div);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/15.png" alt></p>
<h4 id="5、封装例子"><a href="#5、封装例子" class="headerlink" title="5、封装例子"></a>5、封装例子</h4><ul>
<li>将AJAX请求封装成ajax()方法，它接受一个配置对象params</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">params</span>) </span>&#123;   </span><br><span class="line">  params = params || &#123;&#125;;   </span><br><span class="line">  params.data = params.data || &#123;&#125;;   </span><br><span class="line">  <span class="comment">// 判断是ajax请求还是jsonp请求</span></span><br><span class="line">  <span class="keyword">var</span> json = params.jsonp ? jsonp(params) : json(params);   </span><br><span class="line">  <span class="comment">// ajax请求   </span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">json</span>(<span class="params">params</span>) </span>&#123;   </span><br><span class="line">    <span class="comment">//  请求方式，默认是GET</span></span><br><span class="line">    params.type = (params.type || <span class="string">'GET'</span>).toUpperCase(); </span><br><span class="line">    <span class="comment">// 避免有特殊字符，必须格式化传输数据  </span></span><br><span class="line">    params.data = formatParams(params.data);   </span><br><span class="line">    <span class="keyword">var</span> xhr = <span class="literal">null</span>;    </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 实例化XMLHttpRequest对象   </span></span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">window</span>.XMLHttpRequest) &#123;   </span><br><span class="line">      xhr = <span class="keyword">new</span> XMLHttpRequest();   </span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;   </span><br><span class="line">      <span class="comment">// IE6及其以下版本   </span></span><br><span class="line">      xhr = <span class="keyword">new</span> ActiveXObjcet(<span class="string">'Microsoft.XMLHTTP'</span>);   </span><br><span class="line">    &#125;;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用实例：</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">ajax(&#123;   </span><br><span class="line">  url: <span class="string">'test.php'</span>,   <span class="comment">// 请求地址</span></span><br><span class="line">  type: <span class="string">'POST'</span>,   <span class="comment">// 请求类型，默认"GET"，还可以是"POST"</span></span><br><span class="line">  data: &#123;<span class="string">'b'</span>: <span class="string">'异步请求'</span>&#125;,   <span class="comment">// 传输数据</span></span><br><span class="line">  success: <span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;   <span class="comment">// 请求成功的回调函数</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">JSON</span>.parse(res));   </span><br><span class="line">  &#125;,</span><br><span class="line">  error: <span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;&#125;   <span class="comment">// 请求失败的回调函数</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ul>
<li>这个过程是一定要记在脑子里的</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url, success, fail</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 1. 创建连接</span></span><br><span class="line">    <span class="keyword">var</span> xhr = <span class="literal">null</span>;</span><br><span class="line">    xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">    <span class="comment">// 2. 连接服务器</span></span><br><span class="line">    xhr.open(<span class="string">'get'</span>, url, <span class="literal">true</span>)</span><br><span class="line">    <span class="comment">// 3. 发送请求</span></span><br><span class="line">    xhr.send(<span class="literal">null</span>);</span><br><span class="line">    <span class="comment">// 4. 接受请求</span></span><br><span class="line">    xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(xhr.readyState == <span class="number">4</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(xhr.status == <span class="number">200</span>)&#123;</span><br><span class="line">                success(xhr.responseText);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123; <span class="comment">// fail</span></span><br><span class="line">                fail &amp;&amp; fail(xhr.status);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://poetries1.gitee.io/img-repo/20191001/16.png" alt></p>
<h5 id="谈谈JSONP"><a href="#谈谈JSONP" class="headerlink" title="谈谈JSONP"></a>谈谈JSONP</h5><ul>
<li>要访问web服务器的数据除了XMLHttpRequest外还有一种方法是JSONP</li>
<li><p>如果HTML和JavaScript与数据同时在同一个机器上，就可以使用XMLHttpRequest</p>
</li>
<li><p>什么是JSONP？</p>
<ul>
<li>JSONP(JSON with Padding)是一个非官方的协议，它允许在服务器端集成Script tags返回至客户端，通过javascript callback的形式实现跨域访问（这仅仅是JSONP简单的实现形式）</li>
</ul>
</li>
<li>JSONP有什么用？<ul>
<li>由于同源策略的限制，XmlHttpRequest只允许请求当前源（域名、协议、端口）的资源，为了实现跨域请求，可以通过script标签实现跨域请求，然后在服务端输出JSON数据并执行回调函数，从而解决了跨域的数据请求</li>
</ul>
</li>
<li><p>如何使用JSONP？</p>
<ul>
<li>在客户端声明回调函数之后，客户端通过script标签向服务器跨域请求数据，然后服务端返回相应的数据并动态执行回调函数</li>
</ul>
</li>
<li><p>用XMLHttpRequest时，我们得到一个字符串；要用JSON.parse把字符串转化成对象，使用jsonp时，script标志会解析并执行返回的代码，等我们处理数据时，已经是一个JavaScript对象了</p>
</li>
<li><p>简单实例</p>
</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">content</span>=<span class="string">"text/html; charset=utf-8"</span> <span class="attr">http-equiv</span>=<span class="string">"Content-Type"</span> /&gt;</span>  </span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span>  </span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">jsonpCallback</span>(<span class="params">result</span>) </span>&#123;  </span></span><br><span class="line">        alert(result.a);  </span><br><span class="line">        alert(result.b);  </span><br><span class="line">        alert(result.c);  </span><br><span class="line"><span class="javascript">        <span class="keyword">for</span>(<span class="keyword">var</span> i <span class="keyword">in</span> result) &#123;  </span></span><br><span class="line"><span class="javascript">            alert(i+<span class="string">":"</span>+result[i]);<span class="comment">//循环输出a:1,b:2,etc.  </span></span></span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"http://crossdomain.com/services.php?callback=jsonpCallback"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span>  </span><br><span class="line"><span class="comment">&lt;!--callback参数指示生成JavaScript代码时要使用的函数jsonpcallback--&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>注意浏览器的缓存问题<ul>
<li>在末尾增加一个随机数可避免频繁请求同一个链接出现的缓存问题</li>
<li>`<script type="text/javascript" src="http://crossdomain.com/services.php?callback=jsonpCallback&random=(new Date()).getTime()"></script>  </li>
</ul>
</li>
</ul>
<p><strong>原生JavaScript实现完整的Ajax、JSONP例子</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">params</span>) </span>&#123;</span><br><span class="line">	params = params || &#123;&#125;;</span><br><span class="line">	params.data = params.data || &#123;&#125;;</span><br><span class="line">	<span class="keyword">var</span> json = params.jsonp ? jsonp(params) : json(params);</span><br><span class="line">	<span class="comment">// ajax请求</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">json</span>(<span class="params">params</span>) </span>&#123;</span><br><span class="line">		params.type = (params.type || <span class="string">'GET'</span>).toUpperCase();</span><br><span class="line">		params.data = formatParams(params.data);</span><br><span class="line">		<span class="keyword">var</span> xhr = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 实例化XMLHttpRequest对象</span></span><br><span class="line">		<span class="keyword">if</span>(<span class="built_in">window</span>.XMLHttpRequest) &#123;</span><br><span class="line">			xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// IE6及其以下版本</span></span><br><span class="line">			xhr = <span class="keyword">new</span> ActiveXObjcet(<span class="string">'Microsoft.XMLHTTP'</span>);</span><br><span class="line">		&#125;;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 监听事件</span></span><br><span class="line">		xhr.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">			<span class="keyword">if</span>(xhr.readyState == <span class="number">4</span>) &#123;</span><br><span class="line">				<span class="keyword">var</span> status = xhr.status;</span><br><span class="line">				<span class="keyword">if</span>(status &gt;= <span class="number">200</span> &amp;&amp; status &lt; <span class="number">300</span>) &#123;</span><br><span class="line">					<span class="keyword">var</span> response = <span class="string">''</span>;</span><br><span class="line">					<span class="keyword">var</span> type = xhr.getResponseHeader(<span class="string">'Content-type'</span>);</span><br><span class="line">					<span class="keyword">if</span>(type.indexOf(<span class="string">'xml'</span>) !== <span class="number">-1</span> &amp;&amp; xhr.responseXML) &#123;</span><br><span class="line">						response = xhr.responseXML; <span class="comment">//Document对象响应</span></span><br><span class="line">					&#125; <span class="keyword">else</span> <span class="keyword">if</span>(type === <span class="string">'application/json'</span>) &#123;</span><br><span class="line">						response = <span class="built_in">JSON</span>.parse(xhr.responseText); <span class="comment">//JSON响应</span></span><br><span class="line">					&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">						response = xhr.responseText; <span class="comment">//字符串响应</span></span><br><span class="line">					&#125;;</span><br><span class="line">					params.success &amp;&amp; params.success(response);</span><br><span class="line">				&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">					params.error &amp;&amp; params.error(status);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 连接和传输数据</span></span><br><span class="line">		<span class="keyword">if</span>(params.type == <span class="string">'GET'</span>) &#123;</span><br><span class="line">			xhr.open(params.type, params.url + <span class="string">'?'</span> + params.data, <span class="literal">true</span>);</span><br><span class="line">			xhr.send(<span class="literal">null</span>);</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			xhr.open(params.type, params.url, <span class="literal">true</span>);</span><br><span class="line">			<span class="comment">//设置提交时的内容类型</span></span><br><span class="line">			xhr.setRequestHeader(<span class="string">'Content-Type'</span>, <span class="string">'application/x-www-form-urlencoded; charset=UTF-8'</span>);</span><br><span class="line">			xhr.send(params.data);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// jsonp请求</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">jsonp</span>(<span class="params">params</span>) </span>&#123;</span><br><span class="line">		<span class="comment">//创建script标签并加入到页面中</span></span><br><span class="line">		<span class="keyword">var</span> callbackName = params.jsonp;</span><br><span class="line">		<span class="keyword">var</span> head = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'head'</span>)[<span class="number">0</span>];</span><br><span class="line">		<span class="comment">// 设置传递给后台的回调参数名</span></span><br><span class="line">		params.data[<span class="string">'callback'</span>] = callbackName;</span><br><span class="line">		<span class="keyword">var</span> data = formatParams(params.data);</span><br><span class="line">		<span class="keyword">var</span> script = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</span><br><span class="line">		head.appendChild(script);</span><br><span class="line"></span><br><span class="line">		<span class="comment">//创建jsonp回调函数</span></span><br><span class="line">		<span class="built_in">window</span>[callbackName] = <span class="function"><span class="keyword">function</span>(<span class="params">json</span>) </span>&#123;</span><br><span class="line">			head.removeChild(script);</span><br><span class="line">			clearTimeout(script.timer);</span><br><span class="line">			<span class="built_in">window</span>[callbackName] = <span class="literal">null</span>;</span><br><span class="line">			params.success &amp;&amp; params.success(json);</span><br><span class="line">		&#125;;</span><br><span class="line"></span><br><span class="line">		<span class="comment">//发送请求</span></span><br><span class="line">		script.src = params.url + <span class="string">'?'</span> + data;</span><br><span class="line"></span><br><span class="line">		<span class="comment">//超时处理</span></span><br><span class="line">		<span class="keyword">if</span>(params.time) &#123;</span><br><span class="line">			script.timer = setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">				<span class="built_in">window</span>[callbackName] = <span class="literal">null</span>;</span><br><span class="line">				head.removeChild(script);</span><br><span class="line">				params.error &amp;&amp; params.error(&#123;</span><br><span class="line">					message: <span class="string">'超时'</span></span><br><span class="line">				&#125;);</span><br><span class="line">			&#125;, time);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line">	<span class="comment">//格式化参数</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">formatParams</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">var</span> arr = [];</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">var</span> name <span class="keyword">in</span> data) &#123;</span><br><span class="line">			arr.push(<span class="built_in">encodeURIComponent</span>(name) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(data[name]));</span><br><span class="line">		&#125;;</span><br><span class="line">		<span class="comment">// 添加一个随机数，防止缓存</span></span><br><span class="line">		arr.push(<span class="string">'v='</span> + random());</span><br><span class="line">		<span class="keyword">return</span> arr.join(<span class="string">'&amp;'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 获取随机数</span></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">random</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">10000</span> + <span class="number">500</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">ajax(&#123;</span><br><span class="line">				url: <span class="string">'get.php'</span>,</span><br><span class="line">				type: <span class="string">'GET'</span>,</span><br><span class="line">				data: &#123;<span class="string">'intro'</span>: <span class="string">'get请求'</span>&#125;,</span><br><span class="line">				success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">					res = <span class="built_in">JSON</span>.parse(res);</span><br><span class="line">					<span class="built_in">document</span>.getElementById(<span class="string">'a'</span>).innerHTML = res.intro;</span><br><span class="line">					<span class="built_in">console</span>.log(res);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		ajax(&#123;</span><br><span class="line">				url: <span class="string">'post.php'</span>,</span><br><span class="line">				type: <span class="string">'POST'</span>,</span><br><span class="line">				data: &#123;<span class="string">'intro'</span>: <span class="string">'post请求'</span>&#125;,</span><br><span class="line">				success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">					res = <span class="built_in">JSON</span>.parse(res);</span><br><span class="line">					<span class="built_in">document</span>.getElementById(<span class="string">'b'</span>).innerHTML = res.intro;</span><br><span class="line">					<span class="built_in">console</span>.log(res);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		ajax(&#123;</span><br><span class="line">				url: <span class="string">'http://music.qq.com/musicbox/shop/v3/data/hit/hit_all.js'</span>,</span><br><span class="line">				jsonp: <span class="string">'jsonpCallback'</span>,</span><br><span class="line">				data: &#123;<span class="string">'callback'</span>: <span class="string">'jsonpCallback'</span>&#125;,</span><br><span class="line">				success:<span class="function"><span class="keyword">function</span>(<span class="params">res</span>)</span>&#123;</span><br><span class="line">					JsonCallback(json);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>下面我们就根据以上 封装的例子跨域获取qq音乐的数据</p>
</blockquote>
<ul>
<li><a href="http://codepen.io/poetries/pen/oBMKmG" target="_blank" rel="noopener">在线演示–跨域获取qq音乐的数据</a></li>
</ul>
<p><strong>下面的方法也可以实现</strong></p>
<ul>
<li>使用jQuery实现</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;script src=<span class="string">"jquery-3.1.0.min.js"</span>&gt;&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">		&lt;script type="text/</span>javascript<span class="string">"&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">			$.ajax(&#123;</span></span><br><span class="line"><span class="string">				  type: "</span><span class="keyword">get</span>",</span><br><span class="line">				  async: false,</span><br><span class="line">				  url: "http://music.qq.com/musicbox/shop/v3/data/hit/hit_all.js",</span><br><span class="line">				  dataType: "jsonp",</span><br><span class="line">				  jsonp: "callback",</span><br><span class="line">				  jsonpCallback: "JsonCallback",</span><br><span class="line">				  scriptCharset: 'GBK',//设置编码，否则会乱码</span><br><span class="line">				  success: function(data) &#123;</span><br><span class="line">				    <span class="comment">//var result = JSON.stringify(data);</span></span><br><span class="line">					  JsonCallback(data);</span><br><span class="line">				  &#125;,</span><br><span class="line">				  error: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">				    alert(<span class="string">'fail'</span>);</span><br><span class="line">				  &#125;</span><br><span class="line">				&#125;);</span><br><span class="line">			<span class="function"><span class="keyword">function</span> <span class="title">JsonCallback</span>(<span class="params">json</span>)</span>&#123;</span><br><span class="line">				<span class="keyword">var</span> data = json.songlist;</span><br><span class="line">				<span class="keyword">var</span> html = <span class="string">''</span>;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;data.length;i++) &#123;</span><br><span class="line">					<span class="built_in">document</span>.write(data[i].url+<span class="string">"&lt;br&gt;"</span>);</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">			&#125;</span><br><span class="line">		&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">```      </span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">- 原生js简洁实现</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">```javascript</span></span><br><span class="line"><span class="regexp">var script = document.createElement("script");</span></span><br><span class="line"><span class="regexp">			script.src = 'http:/</span><span class="regexp">/music.qq.com/mu</span>sicbox/shop/v3/data/hit/hit_all.js?callback=JsonCallback<span class="string">';</span></span><br><span class="line"><span class="string">			document.body.appendChild(script);</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">			function JsonCallback(json)&#123;</span></span><br><span class="line"><span class="string">				var data = json.songlist;</span></span><br><span class="line"><span class="string">				var html = '</span><span class="string">';</span></span><br><span class="line"><span class="string">				for (var i=0;i&lt;data.length;i++) &#123;</span></span><br><span class="line"><span class="string">					console.log(data[i]);</span></span><br><span class="line"><span class="string">				&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">			&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="三、-jQuery中的Ajax"><a href="#三、-jQuery中的Ajax" class="headerlink" title="三、 jQuery中的Ajax"></a>三、 jQuery中的Ajax</h3><ul>
<li>jQuery中的<code>ajax</code>封装案例</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//ajax请求后台数据</span></span><br><span class="line"><span class="keyword">var</span> btn =  <span class="built_in">document</span>.getElementsByTagName(<span class="string">"input"</span>)[<span class="number">0</span>];</span><br><span class="line">btn.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	</span><br><span class="line">	ajax(&#123;<span class="comment">//json格式</span></span><br><span class="line">		type:<span class="string">"post"</span>,</span><br><span class="line">		url:<span class="string">"post.php"</span>,</span><br><span class="line">		data:<span class="string">"username=poetries&amp;pwd=123456"</span>,</span><br><span class="line">		asyn:<span class="literal">true</span>,</span><br><span class="line">		success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">			<span class="built_in">document</span>.write(data);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//封装ajax</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">aJson</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> ajx = <span class="literal">null</span>;</span><br><span class="line">	<span class="keyword">var</span> type = aJson.type || <span class="string">"get"</span>;</span><br><span class="line">	<span class="keyword">var</span> asyn = aJson.asyn || <span class="literal">true</span>;</span><br><span class="line">	<span class="keyword">var</span> url = aJson.url;		<span class="comment">// url 接收 传输位置</span></span><br><span class="line">	<span class="keyword">var</span> success = aJson.success;<span class="comment">// success 接收 传输完成后的回调函数</span></span><br><span class="line">	<span class="keyword">var</span> data = aJson.data || <span class="string">''</span>;<span class="comment">// data 接收需要附带传输的数据</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">window</span>.XMLHttpRequest)&#123;<span class="comment">//兼容处理</span></span><br><span class="line">		ajx = <span class="keyword">new</span> XMLHttpRequest();<span class="comment">//一般浏览器</span></span><br><span class="line">	&#125;<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		ajx = <span class="keyword">new</span> ActiveXObject(<span class="string">"Microsoft.XMLHTTP"</span>);<span class="comment">//IE6+</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (type == <span class="string">"get"</span> &amp;&amp; data)</span><br><span class="line">	&#123;</span><br><span class="line">		url +=<span class="string">"/?"</span>+data+<span class="string">"&amp;"</span>+<span class="built_in">Math</span>.random();</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//初始化ajax请求</span></span><br><span class="line">	ajx.open( type , url , asyn );</span><br><span class="line">	<span class="comment">//规定传输数据的格式</span></span><br><span class="line">	ajx.setRequestHeader(<span class="string">'content-type'</span>,<span class="string">'application/x-www-form-urlencoded'</span>);</span><br><span class="line">	<span class="comment">//发送ajax请求（包括post数据的传输）</span></span><br><span class="line">	type == <span class="string">"get"</span> ?ajx.send():ajx.send(aJson.data);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//处理请求</span></span><br><span class="line">	ajx.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params">aJson</span>)</span>&#123;</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">if</span>(ajx.readState == <span class="number">4</span>)&#123;</span><br><span class="line">			</span><br><span class="line">		<span class="keyword">if</span> (ajx.status == <span class="number">200</span> &amp;&amp; ajx.status&lt;<span class="number">300</span>)<span class="comment">//200是HTTP 请求成功的状态码</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">//请求成功处理数据</span></span><br><span class="line">			success &amp;&amp; success(ajx.responseText);</span><br><span class="line">		&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">			alert(<span class="string">"请求出错"</span>+ajx.status);</span><br><span class="line">			</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h4 id="jQuery中的Ajax的一些方法"><a href="#jQuery中的Ajax的一些方法" class="headerlink" title="jQuery中的Ajax的一些方法"></a>jQuery中的Ajax的一些方法</h4><p><code>jquery</code>对<code>Ajax</code>操作进行了封装，在<code>jquery</code>中的<code>$.ajax()</code>方法属于最底层的方法，第<code>2</code>层是<code>load()</code>、<code>$.get()</code>、<code>$.post();</code>第<code>3</code>层是<code>$.getScript()</code>、<code>$.getJSON()</code>，第<code>2</code>层使用频率很高 </p>
<h5 id="load-方法"><a href="#load-方法" class="headerlink" title="load()方法"></a><code>load()</code>方法</h5><ul>
<li><code>load()</code>方法是<code>jquery</code>中最简单和常用的<code>ajax</code>方法，能载入远程<code>HTML</code>代码并插入<code>DOM</code>中 结构为：<code>load(url,[data],[callback])</code><ul>
<li>使用<code>url</code>参数指定选择符可以加载页面内的某些元素 <code>load</code>方法中<code>url</code>语法：<code>url selector</code> 注意：<code>url</code>和选择器之间有一个空格</li>
</ul>
</li>
<li>传递方式<ul>
<li><code>load()</code>方法的传递方式根据参数<code>data</code>来自动指定，如果没有参数传递，则采用<code>GET</code>方式传递，反之，采用<code>POST</code></li>
</ul>
</li>
<li>回调参数<ul>
<li>必须在加载完成后才执行的操作，该函数有三个参数 分别代表请求返回的内容、请求状态、<code>XMLHttpRequest</code>对象</li>
<li>只要请求完成，回调函数就会被触发</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$(<span class="string">"#testTest"</span>).load(<span class="string">"test.html"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">responseText,textStatus,XMLHttpRequest</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//respnoseText 请求返回的内容</span></span><br><span class="line">    <span class="comment">//textStatus 请求状态 ：sucess、error、notmodified、timeout</span></span><br><span class="line">    <span class="comment">//XMLHttpRequest </span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>load方法参数</strong></li>
</ul>
<table>
<thead>
<tr>
<th>参数名称</th>
<th>类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>url</code></td>
<td><code>String</code></td>
<td>请求<code>HTML</code>页面的<code>URL</code>地址</td>
</tr>
<tr>
<td><code>data(可选)</code></td>
<td><code>Object</code></td>
<td>发送至服务器的<code>key</code> / <code>value</code>数据</td>
</tr>
<tr>
<td><code>callback(可选)</code></td>
<td><code>Function</code></td>
<td>请求完成时的回调函数，无论是请求成功还是失败</td>
</tr>
</tbody>
</table>
<h5 id="get-和-post-方法"><a href="#get-和-post-方法" class="headerlink" title="$.get()和$.post()方法"></a><code>$.get()</code>和<code>$.post()</code>方法</h5><p><code>load()</code>方法通常用来从web服务器上获取静态的数据文件。在项目中需要传递一些参数给服务器中的页面，那么可以使用<code>$.get()</code>和<code>$.post()</code>或<code>$.ajax()</code>方法</p>
<ul>
<li><p>注意：<code>$.get()</code>和<code>$.post()</code>方法是<code>jquery</code>中的全局函数</p>
</li>
<li><p><strong>$.get()方法</strong></p>
<ul>
<li><code>$.get()</code>方法使用<code>GET</code>方式来进行异步请求</li>
<li>结构为：<code>$.get(url,[data],callback,type)</code><ul>
<li>如果服务器返回的内容格式是<code>xml</code>文档，需要在服务器端设置<code>Content-Type</code>类型 代码如下：<code>header(&quot;Content-Type:text/xml:charset=utf-8&quot;)</code> //<code>php</code></li>
</ul>
</li>
</ul>
</li>
<li><strong><code>$.get()</code>方法参数解析</strong></li>
</ul>
<table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>url</code></td>
<td><code>String</code></td>
<td>请求<code>HTML</code>页的地址</td>
</tr>
<tr>
<td><code>data(可选)</code></td>
<td><code>Object</code></td>
<td>发送至服务器的<code>key</code>/ <code>value</code> 数据会作为<code>QueryString</code>附加到请求URL中</td>
</tr>
<tr>
<td><code>callback(可选)</code></td>
<td><code>Function</code></td>
<td>载入成功的回调函数（只有当<code>Response</code>的返回状态是success才调用该方法）</td>
</tr>
<tr>
<td><code>type(可选)</code></td>
<td><code>String</code></td>
<td>服务器返回内容的格式，包括<code>xml</code>、<code>html</code>、<code>script</code>、<code>json</code>、<code>text</code>和<code>_default</code></td>
</tr>
</tbody>
</table>
<ul>
<li><p><strong>$.post()方法</strong></p>
<ul>
<li>它与<code>$.get()</code>方法的结构和使用方式相同，有如下区别<ul>
<li><code>GET</code>请求会将参数跟张乃URL后进行传递，而<code>POST</code>请求则是作为<code>Http</code>消息的实体内容发送给web服务器，在<code>ajax</code>请求中，这种区别对用户不可见<ul>
<li><code>GET</code>方式对传输数据有大小限制（通常不能大于<code>2KB</code>），而使用<code>POST</code>方式传递的数据量要比<code>GET</code>方式大得多（理论不受限制）</li>
<li><code>GET</code>方式请求的数据会被浏览器缓存起来，因此其他人可以从浏览器的历史纪录中读取这些数据，如：账号、密码。在某种情况下，<code>GET</code>方式会带来严重的安全问题，而<code>POST</code>相对来说可以避免这些问题</li>
<li><code>GET</code>和<code>POST</code>方式传递的数据在服务端的获取也不相同。在<code>PHP</code>中，<code>GET</code>方式用<code>$_GET[]</code>获取；<code>POST</code>方式用<code>$_POST[]</code>获取;两种方式都可用<code>$_REQUEST[]</code>来获取 </li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>总结</strong></p>
<ul>
<li>使用<code>load()</code>、<code>$.get()</code>和<code>$.post()</code>方法完成了一些常规的<code>Ajax</code>程序，如果还需要复杂的<code>Ajax</code>程序，就需要用到<code>$.ajax()</code>方式</li>
</ul>
</li>
</ul>
<h5 id="ajax-方法"><a href="#ajax-方法" class="headerlink" title="$.ajax()方法"></a>$.ajax()方法</h5><ul>
<li><code>$.ajax()</code>方法是<code>jquery</code>最底层的<code>Ajax</code>实现，它的结构为<code>$.ajax(options)</code></li>
<li>该方法只有一个参数，但在这个对象里包含了<code>$.ajax()</code>方式所需要的请求设置以及回调函等信息，参数以<code>key</code> / <code>value</code>存在，所有参数都是可选的</li>
<li><strong>$.ajax()方式常用参数解析</strong></li>
</ul>
<table>
<thead>
<tr>
<th>参数</th>
<th>类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>url</code></td>
<td><code>String</code></td>
<td>(默认为当前页地址)发送请求的地址</td>
</tr>
<tr>
<td><code>type</code></td>
<td><code>String</code></td>
<td>请求方式（<code>POST</code>或<code>GET</code>）默认为<code>GET</code></td>
</tr>
<tr>
<td><code>timeout</code></td>
<td><code>Number</code></td>
<td>设置请求超时时间（毫秒）</td>
</tr>
<tr>
<td><code>dataType</code></td>
<td><code>String</code></td>
<td>预期服务器返回的类型。可用的类型如下<br><br> <strong>xml</strong>:返回<code>XML</code>文档，可用<code>jquery</code>处理<br><strong>html</strong>:返回纯文本的<code>HTML</code>信息，包含的<code>script</code>标签也会在插入<code>DOM</code>时执行<br><strong>script</strong>：返回纯文本的<code>javascript</code>代码。不会自动缓存结果，除非设置<code>cache</code>参数。注意：在远程请求时，所有的<code>POST</code>请求都将转为<code>GET</code>请求<br><strong>json</strong>:返回<code>JSON</code>数据<br><strong>jsonp</strong>:<code>JSONP</code>格式，使用<code>jsonp</code>形式调用函数时，例如：<code>myurl?call back=?,jquery</code>将自动替换后一个<code>？</code>为正确的函数名，以执行回调函数<br><strong>text</strong>:返回纯文本字符串</td>
</tr>
<tr>
<td><code>beforeSend</code></td>
<td><code>Function</code></td>
<td>发送请求前可以修改<code>XMLHttpRequest</code>对象的函数，例如添加自定义<code>HTTP</code>头。在<code>beforeSend</code>中如果返回<code>false</code>可以取消本次<code>Ajax</code>请求。<code>XMLHttpRequest</code>对象是唯一的参数<br> function(XMLHttpRequest){<br>          <code>this</code>;//调用本次<code>Ajax</code>请求时传递的<code>options</code>参数<br>}</td>
</tr>
<tr>
<td><code>complete</code></td>
<td><code>Function</code></td>
<td>请求完成后的回调函数（请求成功或失败时都调用）<br> 参数：<code>XMLHttpRequest</code>对象和一个描述成功请求类型的字符串<br>function(XMLHttpRequest,textStatus){<br>         <code>this</code>;//调用本次Ajax请求时传递的<code>options</code>参数<br>}</td>
</tr>
<tr>
<td><code>success</code></td>
<td><code>Function</code></td>
<td>请求成功后调用的回调函数，有两个参数<br>(1)由服务器返回，并根据<code>dataTyppe</code>参数进行处理后的数据<br>(2)描述状态的字符串<br><code>function</code>(data,textStatus){<br>         //<code>data</code>可能是<code>xmlDoc、`</code>jsonObj<code>、</code>html<code>、</code>text<code>等&lt;br&gt;</code>this<code>;//调用本次</code>Ajax<code>请求时传递的</code>options`参数<br>}</td>
</tr>
<tr>
<td><code>error</code></td>
<td><code>Function</code></td>
<td>请求失败时被调用的函数</td>
</tr>
<tr>
<td><code>global</code></td>
<td><code>Boolean</code></td>
<td>默认为<code>true</code>。表示是否触发全局<code>Ajax</code>事件，设置为<code>false</code>将不会触发。<code>AjaxStart</code>或<code>AjaxStop</code>可用于控制各种<code>Ajax</code>事件</td>
</tr>
</tbody>
</table>
<ul>
<li>参考<ul>
<li>锋利的<code>jQuery</code></li>
</ul>
</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2016/11/26/h5-api/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2016/12/02/Canvas-draw-clock/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
